﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Chinesys.Domain.InputValidations;
using Chinesys.Entities;
using Chinesys.UI.Helpers;
using Chinesys.Domain;
using Chinesys.Domain.BizRules;

namespace Chinesys.UI.Account
{
    public partial class ChangePassword : PageBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            Master.PageTitle = "Cambio de Password";
            validationSummary.Clear();
        }

        protected void ChangePasswordPushButton_Click(object sender, EventArgs e)
        {
            List<InputValidationError> errors = new List<InputValidationError>();

            UserEntity user = User;
            string oldPass = user.Pass;
            string currentPass = TypeHelper.ConvertToType<String>(CurrentPassword.Text, "Password Anterior", errors);
            string newPass = TypeHelper.ConvertToType<String>(NewPassword.Text, "Nuevo Password", errors);
            string confirmPass = TypeHelper.ConvertToType<String>(ConfirmNewPassword.Text, "Confirme Nuevo Password", errors);


            if (oldPass != currentPass)
            {
                hdnBizRulesException.Value = "El password actual ingresado no es el correcto.";
                return;
            }
            if (newPass != confirmPass)
            {
                hdnBizRulesException.Value = "El password nuevo no coincide con la confirmación.";
                return;
            }

            bool success = false;
            if (errors.Any())
            {
                validationSummary.Errors = errors;
            }
            else
            {
                try
                {
                    user.Pass = newPass;
                    UserDomain.UpdatePassword(user);
                    success = true;
                }
                catch (InputValidationException ex)
                {
                    validationSummary.Errors = ex.Validator.Errors;
                }
                catch (BizRulesException ex)
                {
                    hdnBizRulesException.Value = ex.Message;
                }
            }

            if (success)
                Response.Redirect("~/Account/ChangePasswordSuccess.aspx");
        }
    }
}
